package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.EnInfo;
import cn.com.hhrcw.entity.OpJob;
import cn.com.hhrcw.entity.PiInfo;
import cn.com.hhrcw.entity.SysUser;
import cn.com.hhrcw.mapstruct.EnInfoConvert;
import cn.com.hhrcw.mapstruct.OpJobConvert;
import cn.com.hhrcw.params.OpJobParams;
import cn.com.hhrcw.service.IEnInfoService;
import cn.com.hhrcw.service.IOpBrowseHistoryService;
import cn.com.hhrcw.service.IOpJobService;
import cn.com.hhrcw.service.IPiInfoService;
import cn.com.hhrcw.utils.SubjectUtils;
import cn.com.hhrcw.vo.EnInfoVO;
import cn.com.hhrcw.vo.OpJobVO;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.function.Function;

/**
* 职位-职位本位
*
* @author jiangdong
* @since 2020-10-29
*/
@RestController
@Slf4j
@RequestMapping("/personal/opJob")
@Api(tags = "职位-职位本位")
@Validated
public class OpJobController extends JeecgController<OpJob, IOpJobService> {

    @Autowired
    private IOpJobService opJobService;

    @Autowired
    private OpJobConvert opJobConvert;
    @Autowired
    private IEnInfoService enInfoService;
    @Autowired
    private IPiInfoService piInfoService;
    @Autowired
    private EnInfoConvert enInfoConvert;
    @Autowired
    private IOpBrowseHistoryService browseHistoryService;
    /**
    * 分页列表查询
    *
    * @param params 请求参数
    * @return
    */
    @GetMapping(value = "/list")
    @AutoLog("职位-职位本位-分页列表查询")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @PermissionData
    public Result<Page<OpJobVO>> list(OpJobParams params, HttpServletRequest request) {
        QueryWrapper<OpJob> queryWrapper = QueryGenerator.initQueryWrapper(opJobConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        IPage<OpJob> page = opJobService.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<OpJob, OpJobVO> fun = opJob -> opJobConvert.toVO(opJob);

        return Result.ok((Page)page.convert(fun));
    }

    /**
    * 根据id查询
    *
    * @param id 数据id
    * @return
    */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    public Result<?> queryById(String id) {
        OpJob opJob = opJobService
            .lambdaQuery()
            .eq(OpJob::getId,id)
            .eq(OpJob::getDelFlag,false)
            .one();
        if(opJob == null){
            return Result.error(404,"数据不存在");
        }
        Integer count = opJob.getBrowseCount();
        if (null == count){
            opJob.setBrowseCount(1);
        }else {
            opJob.setBrowseCount(count+1);
        }
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        opJobService.updateJobCount(opJob,sysUser);
        OpJobVO jobVO = opJobConvert.toVO(opJob);
        String format = StrUtil.format("{}年-{}年", jobVO.getMinExperience(), jobVO.getMaxExperience());
        jobVO.setWorkExperience(format);
        String companyId = jobVO.getCompanyId();
        EnInfo enInfo = enInfoService.getById(companyId);
        EnInfoVO enInfoVO = enInfoConvert.toVO(enInfo);
        String personnel = enInfoVO.getEnPersonnel();
        if (StrUtil.isNotBlank(personnel)) {
            boolean equals = "10000-99999999".equals(personnel);
            if (equals) {
                enInfoVO.setEnPersonnel("10000以上");
            }
        }
        jobVO.setEnInfoVO(enInfoVO);
        PiInfo info = piInfoService.lambdaQuery().eq(PiInfo::getUserId,jobVO.getCreateBy()).eq(PiInfo::getDelFlag,false).one();
        if (null != info){
            jobVO.setStationName(info.getStationName());
            jobVO.setPhotoUrl(info.getPhotoId());
            jobVO.setRealName(info.getNickName());
        }



        return Result.ok(jobVO);
    }

    /**
    * 添加
    *
    * @param params 请求参数
    * @return
    */
    @PostMapping(value = "/add")
    @AutoLog("职位-职位本位-添加")
    @ApiOperation(value = "添加", notes = "添加")
    @RequiresPermissions("opJob:add")
    public Result<?> add(@RequestBody @Valid OpJobParams params) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        OpJob opJob = opJobConvert.toEntity(params);
        opJob.setCreateBy(sysUser.getId());
        opJob.setCreateTime(DateUtil.date());
        opJob.setDelFlag(false);

        boolean saved = opJobService.save(opJob);
        return saved ? Result.ok() : Result.error("添加失败");
    }

    /**
    * 编辑
    *
    * @param params 请求参数
    * @return
    */
    @PostMapping(value = "/edit")
    @AutoLog("职位-职位本位-编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @RequiresPermissions("opJob:edit")
    public Result<?> edit(@RequestBody @Valid OpJobParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        OpJob opJob = opJobConvert.toEntity(params);
        opJob.setUpdateBy(sysUser.getId());
        opJob.setUpdateTime(DateUtil.date());

        boolean updated = opJobService.updateById(opJob);
        return updated ? Result.ok() : Result.error("编辑失败");
    }


    /**
    * 批量删除
    *
    * @param id 数据id
    * @return
    */
    @GetMapping(value = "/delete")
    @AutoLog("职位-职位本位-批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("opJob:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<OpJob> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(OpJob::getId, id)
            .set(OpJob::getDelFlag, true)
            .set(OpJob::getUpdateBy, sysUser.getUsername())
            .set(OpJob::getUpdateTime, DateUtil.date());

        boolean deleted = opJobService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
    * 属性值是否重复
    *
    * @return
    */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
    * 导出excel
    *
    * @param request
    * @param params
    */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, OpJobParams params) {
        OpJob opJob = opJobConvert.toEntity(params);
        opJob.setDelFlag(false);
        QueryWrapper<OpJob> queryWrapper = QueryGenerator.initQueryWrapper(opJob, request.getParameterMap());
        List<OpJob> data = opJobService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("职位-职位本位", "职位-职位本位");
        String url = super.exportXls(exportParams, OpJobVO.class,opJobConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
        public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, OpJob.class);
    }

}
